"""
配置管理服务
负责初始化和运行配置管理系统
"""

import os
import asyncio
import logging
from typing import Optional
from core.config import ConfigManager
from servers.ConfigServer import ConfigServer
from config import Config


logger = logging.getLogger(__name__)


class ConfigService:
    """配置管理服务类"""

    def __init__(self):
        self.config_manager: Optional[ConfigManager] = None
        self.config_server: Optional[ConfigServer] = None
        self._initialized = False

    async def initialize(self, app) -> bool:
        """初始化配置管理系统"""
        if self._initialized:
            return True

        try:
            # 检查是否启用了配置管理功能
            config_enabled = os.getenv('CONFIG_MANAGEMENT_ENABLED', 'true').lower() == 'true'

            if not config_enabled:
                logger.info("Configuration management system is disabled")
                return True

            logger.info("Initializing configuration management system...")

            # Initialize configuration manager
            db_config = {
                'host': Config.MYSQL_HOST,
                'port': Config.MYSQL_PORT,
                'user': Config.MYSQL_USER,
                'password': Config.MYSQL_PASSWORD,
                'database': Config.MYSQL_DATABASE
            }

            self.config_manager = ConfigManager(db_config)
            await self.config_manager.initialize()

            # Initialize configuration server
            self.config_server = ConfigServer()
            self.config_server.setup_config_manager(self.config_manager)

            # Register configuration management routes to FastAPI application
            self.config_server.register_routes(app)

            # Add configuration manager to application state for other modules to use
            app.state.config_manager = self.config_manager
            app.state.config_server = self.config_server

            self._initialized = True
            logger.info("Configuration management system initialized successfully")

            # Print configuration management interface access address
            host = os.getenv('HOST', '0.0.0.0')
            port = Config.PORT
            logger.info(f"Configuration management interface: http://{host}:{port}/admin/config")

            return True

        except Exception as e:
            logger.error(f"Configuration management system initialization failed: {e}")
            # Configuration management failure should not block entire application startup
            return False

    async def shutdown(self):
        """Shutdown configuration management system"""
        try:
            if self.config_manager:
                # Gracefully shutdown configuration manager
                await self.config_manager.shutdown()
                logger.info("Configuration management system shutdown completed")

        except Exception as e:
            logger.error(f"Error during configuration management system shutdown: {e}")

    @property
    def is_initialized(self) -> bool:
        """Check if initialized"""
        return self._initialized

    def get_config_manager(self) -> Optional[ConfigManager]:
        """Get configuration manager instance"""
        return self.config_manager

    def get_config_server(self) -> Optional[ConfigServer]:
        """Get configuration server instance"""
        return self.config_server


# Global configuration service instance
config_service = ConfigService()


def get_config_service() -> ConfigService:
    """Get configuration service instance"""
    return config_service


async def init_config_service(app) -> bool:
    """Initialize configuration service (for lifespan.py to call)"""
    return await config_service.initialize(app)


async def shutdown_config_service():
    """Shutdown configuration service (for lifespan.py to call)"""
    await config_service.shutdown()